

#import "LYLPhotoTailoringViewController.h"
#import "PhotoMaskView.h"
#import "UIImage+Crop.h"

@interface LYLPhotoTailoringViewController ()<UIScrollViewDelegate,PhotoMaskViewDelegate>
{
    CGRect            _rect;
    UIImageView      *_imageView;
    UIView           *_cropView;
    UIEdgeInsets      _imageInset;
    CALayer           *_layer;
    CGFloat           _rotate;
    UIImageView *imgVip;
    UISlider *usl;
    UISwitch *sw;
}

@property (nonatomic,strong) PhotoMaskView *maskView;
@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) UIButton *btn;

@end

@implementation LYLPhotoTailoringViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    _rotate = 0;
    self.view.backgroundColor = [UIColor blackColor];
    self.oldImage =  [UIImage fitScreenWithImage:self.oldImage];
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH)];
    _scrollView.delegate = self;
    
    _imageView = [[UIImageView alloc] initWithImage:self.oldImage];
    _imageView.center = self.scrollView.center;
    
    self.scrollView.contentSize = self.oldImage.size;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.bounces = YES;
    [self.scrollView addSubview:_imageView];
      [self.view addSubview:self.scrollView];
    // maskView
    CGFloat height = 0;
    CGFloat width = 0;
    self.cropHeight?height = self.cropHeight:0;
    if ( self.mode == PhotoMaskViewModeCircle) {
        if (self.cropWidth) {
            height = self.cropWidth;
            self.cropHeight = self.cropWidth;
            width = height;
        }else{
            width = self.cropHeight;
            self.cropWidth = self.cropHeight;
            height = width;
        }
    }else{
        height = self.cropHeight;
        width = self.cropWidth;
    }
    _maskView = [[PhotoMaskView alloc] initWithFrame:self.scrollView.bounds width:width height:height];
    _maskView.mode = self.mode;
    _maskView.userInteractionEnabled = NO;

    _isDark?_maskView.isDark = YES:0;
    _lineColor?_maskView.lineColor = _lineColor:0;
    [self.view addSubview:self.maskView];
    self.maskView.delegate = self;
    [self bottomView];
   
}

-(void)bottomView
{
    CGFloat h = SCREEN_HEIGHT-SCREEN_WIDTH;
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - h, SCREEN_WIDTH, h)];
    [bottomView setBackgroundColor:UIColor.whiteColor];
    
    
    imgVip = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20 + (44-36)/2, 104, 36)];
    [imgVip setBackgroundColor:UIColor.clearColor];
    [bottomView addSubview:imgVip];
    
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(134, 20, SCREEN_WIDTH - 200, 44)];
    [lab setText:@"开启全屏背景透明"];
    [lab setFont:FontFiftent];
    [bottomView addSubview:lab];
    
    sw = [[UISwitch alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 71, 20 + (44-31)/2, 51, 31)];
    [sw setOn:NO];
    [bottomView addSubview:sw];
    
    UIView *l1 = [[UIView alloc] initWithFrame:CGRectMake(0, 20 + 54, SCREEN_WIDTH, 1)];
    l1.backgroundColor = LINE_COLOR;
    [bottomView addSubview:l1];
    
    
    UILabel *labTag = [[UILabel alloc] initWithFrame:CGRectMake(20, CGRectGetMaxY(l1.frame)+10, 60, 44)];
    [labTag setText:@"透明度"];
    [labTag setFont:FontFiftent];
    [bottomView addSubview:labTag];
    
    
    usl = [[UISlider alloc] initWithFrame:CGRectMake(80, CGRectGetMaxY(l1.frame)+10, SCREEN_WIDTH - 110, 44)];
    usl.value = 1.0;
    usl.minimumValue = 0;
    usl.maximumValue = 1.0f;
    [usl addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
    [bottomView addSubview:usl];
    
    
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(usl.frame) + 10, SCREEN_WIDTH, 0.5)];
     lineView.backgroundColor = LINE_COLOR;
    [bottomView addSubview:lineView];
    
    [self.view addSubview:bottomView];
    
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(10, h-50, ScreenWidth-20, 44);
    [btn setTitle:@"使用" forState:UIControlStateNormal];
    btn.titleLabel.font = FontSeventeen;
    [btn addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside];
    [btn setTitleColor:UIColorFromRGB(TextWhiteColor) forState:UIControlStateNormal];
    [btn setBackgroundColor:UIColorFromRGB(BgTitleColor)];
    btn.layer.cornerRadius = 6.0f;
    
    [bottomView addSubview:btn];
    
    [self loadBegin];
    
}

-(void)valueChanged:(UISlider *) sl{
    _imageView.alpha = sl.value;
}

-(void)backBtn
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(imageCropperDidCancel:)]) {
        [self.delegate imageCropperDidCancel:self];
    }
}
- (void)buttonClicked
{
    UIImage *editedImage = [self cropImage];
    NSData *data = UIImageJPEGRepresentation(editedImage,0.5);
    NSString *api = API_UploadWallpaper;
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [ImageUploadUtil uploadImage:data api:api param:@{@"session_uid":[UserUtil getUser].user_id} callback:^(NSString *imageurl, NSDictionary *videoDict, NSString *message) {
        NSLog(@"%@",videoDict);
        
        if(videoDict){
           
            
                [NetworkUtil POST:API_Setwallpaper parameters:
                 @{@"session_uid":[UserUtil getUser].user_id,
                   @"wallpaper_id":convertToString(videoDict[@"wallpaper_id"]),
                   @"wallpaper_full_screen":convertIntToString(self->sw.isOn),
                   @"wallpaper_trans":[NSString stringWithFormat:@"%0.1f",self->usl.value]
                   } success:^(id responseObject, NSDictionary *dict) {
                    NSLog(@"%@",dict);
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                    
                    if (self.delegate && [self.delegate respondsToSelector:@selector(imageCropper:didFinished:dict:)]) {
                        [self.delegate imageCropper:self didFinished:editedImage dict:dict];
                    }
                    
                } failure:^(NSError *error, NSString *message) {
                    [PopUtil showMessage:message];
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                }];
        }else{
            [PopUtil showMessage:message];
            
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }
        
    }];
    
}

-(void)layoutScrollViewWithRect:(CGRect)rect
{
    _rect = rect;
    CGFloat top = (self.oldImage.size.height-rect.size.height)/2;
    CGFloat left = (self.oldImage.size.width-rect.size.width)/2;
    CGFloat bottom = _scrollView.frame.size.height-top-rect.size.height;
    CGFloat right = self.view.bounds.size.width-rect.size.width-left;
    self.scrollView.contentInset = UIEdgeInsetsMake(top, left, bottom, right);
    CGFloat maskCircleWidth = rect.size.width;
    
    CGSize imageSize = self.oldImage.size;
    //setp 2: setup contentSize:
    CGFloat minimunZoomScale = imageSize.width < imageSize.height ? maskCircleWidth / imageSize.width : maskCircleWidth / imageSize.height;
    CGFloat maximumZoomScale = 1.5;
    self.scrollView.minimumZoomScale = minimunZoomScale;
    self.scrollView.maximumZoomScale = maximumZoomScale;
    self.scrollView.zoomScale = self.scrollView.zoomScale < minimunZoomScale ? minimunZoomScale : self.scrollView.zoomScale;
    _imageInset = self.scrollView.contentInset;
    
}
- (UIImage *)cropImage
{
    CGFloat zoomScale = _scrollView.zoomScale;
    
    CGFloat offsetX = _scrollView.contentOffset.x;
    CGFloat offsetY = _scrollView.contentOffset.y;
    CGFloat aX = offsetX>=0 ? offsetX+_imageInset.left : (_imageInset.left - ABS(offsetX));
    CGFloat aY = offsetY>=0 ? offsetY+_imageInset.top : (_imageInset.top - ABS(offsetY));
    
    aX = aX / zoomScale;
    aY = aY / zoomScale;
    
    CGFloat aWidth =  MAX(self.cropWidth / zoomScale, self.cropWidth);
    CGFloat aHeight = MAX(self.cropHeight / zoomScale, self.cropHeight);
    if (zoomScale>1) {
        aWidth = self.cropWidth/zoomScale;
        aHeight = self.cropHeight/zoomScale;
    }
    
    UIImage *image = [self.oldImage cropImageWithX:aX y:aY width:aWidth height:aHeight];
    image = [UIImage imageWithImageSimple:image scaledToSize:CGSizeMake(self.cropWidth, self.cropHeight)];
    return image;
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return _imageView;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    [UIApplication sharedApplication].statusBarHidden = YES;
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
    [UIApplication sharedApplication].statusBarHidden = NO;
}


-(void)loadBegin{
    NSLog(@"调用我----------");
    [NetworkUtil POST:API_GetMyvipdetail parameters:@{@"session_uid":[UserUtil getUser].user_id,@"page_size":@"30"} success:^(id responseObject, NSDictionary *dictionary) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSDictionary *dict = dictionary[@"data"][@"vip_info"];
        if(dict){
            
            [self->imgVip setImage:[UIImage imageNamed:@"vip"]];
            self->sw.enabled = YES;
            self->usl.enabled = YES;
            
        }else{
            [self->imgVip setImage:[UIImage imageNamed:@"vip 未开通"]];
            self->sw.enabled = NO;
            self->usl.enabled = NO;
        }
        
    } failure:^(NSError *error, NSString *message) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}


@end
